package com.jpcc.vw.onlineRadio.activity;

import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Popup;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.net.ConnectivityManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.RemoteException;
import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
/*Start by menglingqiang*/
import android.util.Log;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
/*End by menglingqiang*/

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.cns.android.atmospherelamp.AtmosphereLampManager;
import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.stmt.DeleteBuilder;
import com.jpcc.vw.onlineRadio.R;
import com.jpcc.vw.onlineRadio.adapter.CommonFavouritePaiedHistoryAdapter;
import com.jpcc.vw.onlineRadio.application.MusicApplication;
import com.jpcc.vw.onlineRadio.constants.Constants;
import com.jpcc.vw.onlineRadio.db.DatabaseHelperOrm;
import com.jpcc.vw.onlineRadio.db.DownloadTrackDbBean;
import com.jpcc.vw.onlineRadio.db.FavouriteAlbumDbBean;
import com.jpcc.vw.onlineRadio.model.IRadio;
import com.jpcc.vw.onlineRadio.model.action.DeleteDownloadAlbumAction;
import com.jpcc.vw.onlineRadio.model.action.DeleteFavouriteAction;
import com.jpcc.vw.onlineRadio.model.action.RadioItemSelectedAction;
import com.jpcc.vw.onlineRadio.model.action.WaveAction;
import com.jpcc.vw.onlineRadio.model.bean.Announcer;
import com.jpcc.vw.onlineRadio.model.bean.BaseBean;
import com.jpcc.vw.onlineRadio.model.bean.BoughtAlbumBean;
import com.jpcc.vw.onlineRadio.model.bean.CommonFavouritePaiedHistoryEntity;
import com.jpcc.vw.onlineRadio.model.bean.LiveRadioDetailBean;
import com.jpcc.vw.onlineRadio.model.bean.PaidAlbumsEntity;
import com.jpcc.vw.onlineRadio.model.bean.PaiedAlbumBean;
import com.jpcc.vw.onlineRadio.model.bean.RadioDeailBean;
import com.jpcc.vw.onlineRadio.model.bean.RadioSumBean;
import com.jpcc.vw.onlineRadio.model.bean.RecentAlbumRadioTrackBean;
import com.jpcc.vw.onlineRadio.model.bean.SubordinatedAlbum;
import com.jpcc.vw.onlineRadio.model.bean.Track;
import com.jpcc.vw.onlineRadio.model.impl.RadioImpl;
import com.jpcc.vw.onlineRadio.service.AlbumRadioAudioPlayer;
import com.jpcc.vw.onlineRadio.utils.CommonSubscriber;
import com.jpcc.vw.onlineRadio.utils.ProcessInfoUtils;
import com.jpcc.vw.onlineRadio.utils.SyncFavUtils;
import com.jpcc.vw.onlineRadio.utils.SyncHistoryUtils;
import com.jpcc.vw.onlineRadio.utils.ToastUtils;
import com.jpcc.vw.onlineRadio.utils.TrackUtils;
import com.jpcc.vw.tracelog.TracelogInterface;
import com.lzy.okhttpserver.download.DownloadManager;
import com.orhanobut.logger.Logger;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadmoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.io.File;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import de.greenrobot.event.EventBus;
import rx.Observable;
import rx.Subscriber;
import rx.functions.Action0;
import rx.functions.Func2;

/**
 * 作为我的list中的favourite、paied、history页面的横向滑动列表画面
 */
public class FavouritePaiedHistoryActivity extends com.jpcc.vw.onlineRadio.base.BaseActivity {

    @BindView(R.id.recyclerview_common)
    RecyclerView recyclerview_common;
    @BindView(R.id.layout_back)
    RelativeLayout layout_back;
    @BindView(R.id.swipe_refrsh_common)
    SmartRefreshLayout swipe_refrsh_common;
    @BindView(R.id.layout_search)
    RelativeLayout layout_search;
    @BindView(R.id.tv_title)
    TextView tv_title;
    @BindView(R.id.tv_delete_all)
    TextView tv_delete_all;
    @BindView(R.id.layout_deleteAll)
    RelativeLayout layout_deleteAll;
    @BindView(R.id.tv_show_empty)
    TextView tv_show_empty;
    @BindView(R.id.imv_top_bottom_line)
    ImageView imv_top_bottom_line;
    @BindView(R.id.progress_circular)
    ProgressBar progress_circular;
    @BindView(R.id.imv_new_search)
    ImageView imv_new_search;

    private IRadio radioModel;
    private DatabaseHelperOrm helper;
    private CommonFavouritePaiedHistoryAdapter adapter;
    private List<CommonFavouritePaiedHistoryEntity> datas = new ArrayList<>();
    private int type = 0;
    private boolean is_refresh = true;
    private int page_index = 1;
    private MaterialDialog progressDialog;
    private BroadcastReceiver receiver;
    private Handler popActionHandler;

    @Override
    public int getLayoutId() {
        return R.layout.activity_favourite_paied_history;
    }


    @Override
    public void initProgressDialog() {
        progressDialog = new MaterialDialog.Builder(this)
                .progress(true, 0)
                .content(getResources().getString(R.string.string_102))
                .autoDismiss(false)
                .cancelable(false)
                .build();
    }


    @Override
    public void doAtmosphere(boolean rgbOn, String color) {
        Logger.i("doAtmosphere" + "rgbOn-->" + rgbOn);
        Logger.i("doAtmosphere" + "color-->" + color);
        if (rgbOn) {
            if (TextUtils.isEmpty(color)) {
                imv_top_bottom_line.setColorFilter(Color.TRANSPARENT);
            } else {
                imv_top_bottom_line.setColorFilter(Color.parseColor(color));
            }
        } else {
            imv_top_bottom_line.setColorFilter(Color.TRANSPARENT);
        }
    }

    @Override
    public void showProgress() {
        progressDialog.show();
    }

    @Override
    public void hideProgress() {
        progressDialog.dismiss();
    }

    @Override
    public void setupView() {
        ButterKnife.bind(this);
        layout_search.setVisibility(View.INVISIBLE);
        imv_new_search.setVisibility(View.INVISIBLE);
        radioModel = new RadioImpl();
        helper = DatabaseHelperOrm.getHelper(this);
        EventBus.getDefault().register(this);
        type = getIntent().getIntExtra("KEY_TYPE", 0);
        layout_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                FavouritePaiedHistoryActivity.this.finish();
            }
        });
        imv_new_search.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(FavouritePaiedHistoryActivity.this, SearchActivity.class);
                startActivity(intent);
            }
        });
        adapter = new CommonFavouritePaiedHistoryAdapter(datas, this);
        LinearLayoutManager manager = new LinearLayoutManager(this);
        manager.setItemPrefetchEnabled(false);
//        manager.setOrientation(LinearLayoutManager.HORIZONTAL);
        recyclerview_common.setLayoutManager(manager);
        recyclerview_common.setAdapter(adapter);
        if (type == 2) {
            tv_title.setText(getResources().getString(R.string.string_23));
            tv_show_empty.setText(getResources().getString(R.string.string_96));
            tv_show_empty.setVisibility(View.GONE);
            swipe_refrsh_common.setEnableLoadmore(false);
            swipe_refrsh_common.setEnableRefresh(false);
            swipe_refrsh_common.setOnRefreshListener(new OnRefreshListener() {
                @Override
                public void onRefresh(RefreshLayout refreshlayout) {
                    is_refresh = true;
                    swipe_refrsh_common.setEnableLoadmore(true);
                    getBoughtAlbums();
                }
            });
            swipe_refrsh_common.setOnLoadmoreListener(new OnLoadmoreListener() {
                @Override
                public void onLoadmore(RefreshLayout refreshlayout) {
                    is_refresh = false;
                    getBoughtAlbums();
                }
            });
            is_refresh = true;
            getBoughtAlbums();
        } else {
            swipe_refrsh_common.setEnableLoadmore(false);
            swipe_refrsh_common.setEnableRefresh(false);
        }


        //收藏列表
        if (type == 0) {


            if (Constants.isRelease) {
                ConnectivityManager connectivityManager = (ConnectivityManager) FavouritePaiedHistoryActivity.this.getSystemService(Context.CONNECTIVITY_SERVICE);
                boolean connected = connectivityManager.getNetworkStatus();
                if (!connected) {
                    ToastUtils.show(R.string.string_103);
                }
            }


            tv_title.setText(getResources().getString(R.string.string_12));
            tv_show_empty.setText(getResources().getString(R.string.string_97));
            layout_deleteAll.setVisibility(View.INVISIBLE);
            GetUserFavouriteAlbumRadio();


            if (Constants.isRelease) {
                ConnectivityManager connectivityManager = (ConnectivityManager) FavouritePaiedHistoryActivity.this.getSystemService(Context.CONNECTIVITY_SERVICE);
                boolean connected = connectivityManager.getNetworkStatus();
                if (connected) {
                    showProgress();
                    progress_circular.setVisibility(View.VISIBLE);
                    SyncFavUtils.syncFav(this, new SyncFavUtils.onSyncFav() {
                        @Override
                        public void onSyncFavSuccess() {
                            GetUserFavouriteAlbumRadio();
                            hideProgress();
                            progress_circular.setVisibility(View.INVISIBLE);
                        }

                        @Override
                        public void onsyncFavFail() {
                            ToastUtils.show(getResources().getString(R.string.string_104));
                            progress_circular.setVisibility(View.INVISIBLE);
                            hideProgress();
                        }
                    });
                }
            } else {
                showProgress();
                progress_circular.setVisibility(View.VISIBLE);
                SyncFavUtils.syncFav(this, new SyncFavUtils.onSyncFav() {
                    @Override
                    public void onSyncFavSuccess() {
                        GetUserFavouriteAlbumRadio();
                        hideProgress();
                        progress_circular.setVisibility(View.INVISIBLE);
                    }

                    @Override
                    public void onsyncFavFail() {
                        ToastUtils.show(getResources().getString(R.string.string_104));
                        hideProgress();
                        progress_circular.setVisibility(View.INVISIBLE);
                    }
                });
            }
//            tv_delete_all.setVisibility(View.VISIBLE);
//            layout_deleteAll.setVisibility(View.VISIBLE);
            layout_deleteAll.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    MaterialDialog dialog = new MaterialDialog.Builder(FavouritePaiedHistoryActivity.this).title(getResources().getString(R.string.string_30)).content(getResources().getString(R.string.string_31)).positiveText(getResources().getString(R.string.string_32)).negativeText(getResources().getString(R.string.string_33)).onPositive(new MaterialDialog.SingleButtonCallback() {
                        @Override
                        public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                            DeleteBuilder deleteBuilder = null;
                            try {
                                deleteBuilder = helper.getFavouriteDao().deleteBuilder();
                                deleteBuilder.where().eq("userId", MusicApplication.GetUserId());
                                deleteBuilder.delete();
//                                GetUserFavouriteAlbumRadio();
                                SyncFavUtils.syncFav(FavouritePaiedHistoryActivity.this, new SyncFavUtils.onSyncFav() {
                                    @Override
                                    public void onSyncFavSuccess() {
//                                        ToastUtils.show("Sync success");
                                        GetUserFavouriteAlbumRadio();
                                        hideProgress();
                                    }

                                    @Override
                                    public void onsyncFavFail() {
                                        ToastUtils.show("Sync failed");
                                        hideProgress();
                                    }
                                });
                            } catch (SQLException e) {
                                e.printStackTrace();
                            }
                        }
                    }).build();
                    dialog.show();


                }
            });


            if (Constants.isRelease) {
                ConnectivityManager connectivityManager = (ConnectivityManager) MusicApplication.GetInstance().getSystemService(Context.CONNECTIVITY_SERVICE);
                boolean connected = connectivityManager.getNetworkStatus();
                Logger.i("fav network status-->" + connected);
                if (!connected) {
                    if (ProcessInfoUtils.isForeground(MusicApplication.GetInstance())) {
//                        ToastUtils.show(getResources().getString(R.string.string_87));
                    }
                }
            }

        }
        //下载列表
        //历史列表
        else if (type == 3) {
            tv_title.setText(getResources().getString(R.string.string_24));
//            tv_show_empty.setText(getResources().getString(R.string.string_98));
            prepareHistoryData();
            SyncHistoryUtils.syncHistory(this, null);
        }
        popActionHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                int what = msg.what;
                if (what == 0x01) {
                    try {
                        Bundle bundle = msg.getData();
//                        ToastUtils.show(bundle.getLong("AlbumId") + "");
                        DeleteBuilder deleteBuilder = helper.getDownloadDao().deleteBuilder();
                        deleteBuilder.where().eq("albumId", bundle.getLong("AlbumId"));
                        deleteBuilder.delete();

                        File file = new File(TrackUtils.getTrackDir());

                        DownloadManager downloadManager = DownloadManager.getInstance(FavouritePaiedHistoryActivity.this);
                        if (downloadManager != null) {
                            downloadManager.removeTaskByAlbumId(bundle.getLong("AlbumId") + "");
                        }


                        for (File subFile : file.listFiles()) {
                            if (subFile.getName().startsWith("" + bundle.getLong("AlbumId"))) {
                                subFile.delete();
                            }
                        }

                        initDownloadList();
                    } catch (SQLException e) {
                        e.printStackTrace();
//                        ToastUtils.show("pop error-->" + e.toString());
                    }
                }
            }
        };
        receiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                if (intent != null) {
                    if (intent.getAction().equals("com.jpcc.vw.FavouritePaiedHistoryActivity")) {
                        Bundle bundle = intent.getExtras();
                        if (bundle != null) {
                            if ("DeleteAllDownload".equals(bundle.getString("action"))) {
                                for (CommonFavouritePaiedHistoryEntity entity : datas) {
                                    DeleteBuilder deleteBuilder = null;
                                    try {
                                        deleteBuilder = helper.getDownloadDao().deleteBuilder();
                                        deleteBuilder.where().eq("albumId", entity.getId());
                                        deleteBuilder.delete();
                                        File file = new File(TrackUtils.getTrackDir());
                                        for (File subFile : file.listFiles()) {
                                            if (subFile.getName().startsWith("" + entity.getId())) {
                                                subFile.delete();
                                            }
                                        }
                                    } catch (SQLException e) {
                                        e.printStackTrace();
                                    }
                                }
                                DownloadManager manager = DownloadManager.getInstance(FavouritePaiedHistoryActivity.this);
                                if (manager != null) {
                                    manager.removeAllTask();
                                }
                                initDownloadList();
                            } else if ("CancelFav".equals(bundle.getString("action"))) {
                                DeleteBuilder deleteBuilder = null;
                                try {
                                    deleteBuilder = helper.getFavouriteDao().deleteBuilder();
                                    deleteBuilder.where().eq("id", bundle.getLong("albumId"));
                                    deleteBuilder.delete();
                                    GetUserFavouriteAlbumRadio();
                                } catch (SQLException e) {
                                    e.printStackTrace();
                                }
                            } else if ("DeleteDownloadAlbum".equals(bundle.getString("action"))) {
                                Message msg = Message.obtain();
                                msg.what = 0x01;
                                Bundle bundleExtra = new Bundle();
                                Logger.i("DeleteDownloadAlbum2-->" + bundle.getLong("AlbumId"));
                                bundleExtra.putLong("AlbumId", bundle.getLong("AlbumId"));
                                msg.setData(bundleExtra);
                                popActionHandler.sendMessage(msg);
                            }
                        }
                    }
                }
            }
        };
        IntentFilter filter = new IntentFilter();
        filter.addAction("com.jpcc.vw.FavouritePaiedHistoryActivity");
        this.registerReceiver(receiver, filter);
    }

    @Override
    public void setupData() {
        if (Constants.isRelease) {
            try {
                boolean atmosphereStatus = AtmosphereLampManager.getInstance(this).isHmiAtmosphereLampOn();
                String color = AtmosphereLampManager.getInstance(this).getHmiAtmosphereLampColor();
                doAtmosphere(atmosphereStatus, color);
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }
    }


    private void getBoughtAlbums() {


        if (Constants.isRelease) {
            ConnectivityManager connectivityManager = (ConnectivityManager) FavouritePaiedHistoryActivity.this.getSystemService(Context.CONNECTIVITY_SERVICE);
            boolean connected = connectivityManager.getNetworkStatus();
            if (!connected) {
                ToastUtils.show(R.string.string_88);
                return;
            }
        }


        radioModel.GetBoughtAlbums().doOnSubscribe(new Action0() {
            @Override
            public void call() {
                progress_circular.setVisibility(View.VISIBLE);
            }
        }).subscribe(new CommonSubscriber<BoughtAlbumBean>() {
            @Override
            public void onSuccess(BoughtAlbumBean response) {
                datas.clear();
                progress_circular.setVisibility(View.INVISIBLE);
                if (response.getData() != null && response.getData().size() > 0) {
                    tv_show_empty.setVisibility(View.GONE);
                    for (BoughtAlbumBean.DataBean entity : response.getData()) {
                        CommonFavouritePaiedHistoryEntity result = new CommonFavouritePaiedHistoryEntity();
                        result.setId(entity.getId());
                        result.setName(entity.getAlbumTitle());
                        result.setHostName("");
                        if (entity.getCover() != null && entity.getCover().getLarge() != null) {
                            result.setCoverUrlSmall(entity.getCover().getLarge().getUrl());
                            result.setCoverUrlMiddle(entity.getCover().getLarge().getUrl());
                            result.setCoverUrlLarge(entity.getCover().getLarge().getUrl());
                        }
                        result.setType("album");
                        result.setFrom(2);
                        result.setSample(entity.isSample());
                        result.setVipFree(entity.isVipFree());
                        result.setVipOnly(entity.isVipOnly());
                        datas.add(result);
                    }
                } else {
                    tv_show_empty.setVisibility(View.VISIBLE);
                }
                adapter.setDatas(datas);
            }

            @Override
            public void onFailure(BaseBean response) {
//                if(response.getCode()==Constants.ERROR_CODE_NOT_BIND){
                progress_circular.setVisibility(View.INVISIBLE);
                ToastUtils.show(response.getStatusMessage());
//                }
            }
        });
    }


    private void initDownloadList() {
        if (type == 1) {
            tv_title.setText(getResources().getString(R.string.string_13));
            tv_show_empty.setText(getResources().getString(R.string.string_98));
            prepareDownloadData();
            if (datas == null || datas.size() == 0) {
//                ToastUtils.show(R.string.string_66);
                tv_show_empty.setVisibility(View.VISIBLE);
                layout_deleteAll.setVisibility(View.INVISIBLE);
            } else {
                tv_show_empty.setVisibility(View.GONE);
                layout_deleteAll.setVisibility(View.VISIBLE);
                layout_deleteAll.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (!Constants.isRelease) {
                            MaterialDialog dialog = new MaterialDialog.Builder(FavouritePaiedHistoryActivity.this).title(FavouritePaiedHistoryActivity.this.getResources().getString(R.string.string_30)).content(FavouritePaiedHistoryActivity.this.getResources().getString(R.string.string_31)).positiveText(FavouritePaiedHistoryActivity.this.getResources().getString(R.string.string_32)).negativeText(FavouritePaiedHistoryActivity.this.getResources().getString(R.string.string_33)).onPositive(new MaterialDialog.SingleButtonCallback() {
                                @Override
                                public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                                    for (CommonFavouritePaiedHistoryEntity entity : datas) {
                                        DeleteBuilder deleteBuilder = null;
                                        try {
                                            deleteBuilder = helper.getDownloadDao().deleteBuilder();
                                            deleteBuilder.where().eq("albumId", entity.getId());
                                            deleteBuilder.delete();
                                            File file = new File(TrackUtils.getTrackDir());
                                            for (File subFile : file.listFiles()) {
                                                if (subFile.getName().startsWith("" + entity.getId())) {
                                                    subFile.delete();
                                                }
                                            }
                                        } catch (SQLException e) {
                                            e.printStackTrace();
                                        }
                                    }
                                    DownloadManager manager = DownloadManager.getInstance(FavouritePaiedHistoryActivity.this);
                                    if (manager != null) {
                                        manager.removeAllTask();
                                    }
                                    initDownloadList();
                                }
                            }).build();
                            dialog.show();
                        } else {
                            NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
                            Intent setAlertIntent = new Intent("com.jpcc.vw.FavouritePaiedHistoryActivity");
                            setAlertIntent.putExtra("action", "DeleteAllDownload");
                            PendingIntent pendingIntent = PendingIntent.getBroadcast(FavouritePaiedHistoryActivity.this, 0, setAlertIntent, PendingIntent.FLAG_UPDATE_CURRENT);
                            Popup popup = new Popup(getResources().getString(R.string.string_30), getResources().getString(R.string.string_31));
                            popup.setActionOne(getResources().getString(R.string.string_32), pendingIntent);
                            popup.setActionCancel(getResources().getString(R.string.string_33), "cancel");
                            notificationManager.addPopup(0x0003, popup);
                        }
                    }
                });
            }
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        initDownloadList();
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        adapter.notifyDataSetChanged();
    }

    private void prepareDownloadData() {
        try {
            List<DownloadTrackDbBean> resultQuerys = helper.getDownloadDao().queryBuilder().orderBy("timeStamp", false).groupBy("albumId").where().eq("userId", MusicApplication.GetUserId()).query();
            if (resultQuerys != null) {
                datas.clear();
                for (DownloadTrackDbBean bean : resultQuerys) {
                    datas.add(DownloadTrackDbBean2CommonFavouritePaiedHistoryEntity(bean));
                }
            }
            adapter.setDatas(datas);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }


    private void prepareHistoryData() {
        try {
            List<RecentAlbumRadioTrackBean> localDatas = new ArrayList<>();
            localDatas.addAll(helper.getRecentDao().queryBuilder().groupBy("albumId").orderBy("timeStamp", false).query());
            if (localDatas != null) {
                datas.clear();
                for (RecentAlbumRadioTrackBean bean : localDatas) {
                    datas.add(RecentAlbumRadioTrack2CommonFavouritePaiedHistoryEntity(bean));
                }
            }
            adapter.setDatas(datas);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }


    private CommonFavouritePaiedHistoryEntity RecentAlbumRadioTrack2CommonFavouritePaiedHistoryEntity(RecentAlbumRadioTrackBean input) {
        CommonFavouritePaiedHistoryEntity out = new CommonFavouritePaiedHistoryEntity();
        out.setId(input.getAlbumId());
        out.setType(input.getType());
        out.setFrom(3);
        out.setCpSource("");
        out.setCoverUrlSmall(input.getCover());
        out.setCoverUrlMiddle(input.getCover());
        out.setCoverUrlLarge(input.getCover());
        out.setHostName(input.getAuthor());
        out.setName(input.getAlbumName());
        return out;
    }


    private CommonFavouritePaiedHistoryEntity DownloadTrackDbBean2CommonFavouritePaiedHistoryEntity(DownloadTrackDbBean source) {
        CommonFavouritePaiedHistoryEntity entity = new CommonFavouritePaiedHistoryEntity();
        entity.setId(source.getAlbumId());
        entity.setName(source.getAlbumName());
        entity.setHostName(source.getAuthor());
        entity.setCoverUrlSmall(source.getCover());
        entity.setCoverUrlMiddle(source.getCover());
        entity.setCoverUrlLarge(source.getCover());
        entity.setContentAbstract(source.getAlbumIntro());
//        entity.setCpSource(source.get);
        entity.setFrom(1);
        entity.setType("album");
        return entity;
    }

    /**
     * 获取用户收藏列表
     */
    private void GetUserFavouriteAlbumRadio() {
        List<CommonFavouritePaiedHistoryEntity> local_datas = new ArrayList<>();
        List<FavouriteAlbumDbBean> local_db = new ArrayList<>();
        try {
            local_db.addAll(helper.getFavouriteDao().queryBuilder().orderBy("timeStamp", false).where().eq("userId", MusicApplication.GetUserId()).and().eq("type", "album").query());
            local_db.addAll(helper.getFavouriteDao().queryBuilder().orderBy("timeStamp", false).where().eq("userId", MusicApplication.GetUserId()).and().eq("type", "radio").query());
            if (local_db.size() == 0) {
//                ToastUtils.show(R.string.string_56);
                layout_deleteAll.setVisibility(View.INVISIBLE);
            } else {
                layout_deleteAll.setVisibility(View.INVISIBLE);
            }
            for (FavouriteAlbumDbBean bean : local_db) {
                tv_show_empty.setVisibility(View.GONE);
                if (local_datas.size() < 30) {
                    CommonFavouritePaiedHistoryEntity local = new CommonFavouritePaiedHistoryEntity();
                    local.setId(bean.getId());
                    local.setName(bean.getName());
                    local.setHostName(bean.getHostName());
                    local.setCoverUrlSmall(bean.getCoverUrlLarge());
                    local.setCoverUrlMiddle(bean.getCoverUrlLarge());
                    local.setCoverUrlLarge(bean.getCoverUrlLarge());
                    local.setCpSource(bean.getCpSource());
                    local.setFrom(0);
                    local.setVipFree(bean.isVipFree());
                    local.setType(bean.getType());
                    local_datas.add(local);
                }
            }
            adapter.setDatas(dealDataFromStatus(local_datas));
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    private List<FavouriteAlbumDbBean> getFavRadios() {
        List<FavouriteAlbumDbBean> results = new ArrayList<>();
        try {
            results = DatabaseHelperOrm.getHelper(this).getFavouriteDao().queryBuilder().where().eq("userId", MusicApplication.GetUserId()).and().eq("type", "radio").query();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return results;
    }


    private List<CommonFavouritePaiedHistoryEntity> dealDataFromStatus(List<CommonFavouritePaiedHistoryEntity> sources) {
        List<CommonFavouritePaiedHistoryEntity> results = new ArrayList<>();
        for (CommonFavouritePaiedHistoryEntity sour : sources) {
            sour.setFrom(type);
            results.add(sour);
        }
        return results;
    }


    private void saveDbFav(List<CommonFavouritePaiedHistoryEntity> sources) {
        if (sources != null) {
            for (CommonFavouritePaiedHistoryEntity entity : sources) {
                DatabaseHelperOrm helper = DatabaseHelperOrm.getHelper(this);
                try {
                    Dao dao = helper.getFavouriteDao();
                    dao.create(CommonFavouritePaiedHistoryEntity2FavouriteAlbumDbBean(entity));
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private FavouriteAlbumDbBean CommonFavouritePaiedHistoryEntity2FavouriteAlbumDbBean(CommonFavouritePaiedHistoryEntity input) {
        FavouriteAlbumDbBean out = new FavouriteAlbumDbBean();
        out.setContentAbstract(input.getContentAbstract());
        out.setCoverUrlLarge(input.getCoverUrlLarge());
//        out.setCoverUrlMiddle(input.getCoverUrlMiddle());
//        out.setCoverUrlSmall(input.getCoverUrlSmall());
        out.setCpSource(input.getCpSource());
        out.setHostName(input.getHostName());
        out.setId(input.getId());
        out.setName(input.getName());
        out.setType(input.getType());
        out.setUserId(MusicApplication.GetUserId());
        return out;
    }


    private void CancelUserFavourite(long albumId, String type) {
        if (!Constants.isRelease) {
            MaterialDialog dialog = new MaterialDialog.Builder(this).title(getResources().getString(R.string.string_30)).content(getResources().getString(R.string.string_100)).positiveText(getResources().getString(R.string.string_32)).negativeText(getResources().getString(R.string.string_33)).onPositive(new MaterialDialog.SingleButtonCallback() {
                @Override
                public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                    DeleteBuilder deleteBuilder = null;
                    try {
                        deleteBuilder = helper.getFavouriteDao().deleteBuilder();
                        deleteBuilder.where().eq("id", albumId);
                        deleteBuilder.delete();
                        GetUserFavouriteAlbumRadio();
                    } catch (SQLException e) {
                        e.printStackTrace();
                    }
                }
            }).build();
            dialog.show();
        } else {
//            NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
//            Intent setAlertIntent = new Intent("com.jpcc.vw.FavouritePaiedHistoryActivity");
//            setAlertIntent.putExtra("action", "CancelFav");
//            setAlertIntent.putExtra("albumId", albumId);
//            PendingIntent pendingIntent = PendingIntent.getBroadcast(FavouritePaiedHistoryActivity.this, 0, setAlertIntent, PendingIntent.FLAG_UPDATE_CURRENT);
//            Popup popup = new Popup(getResources().getString(R.string.string_30), getResources().getString(R.string.string_100));
//            popup.setActionOne(getResources().getString(R.string.string_32), pendingIntent);
//            popup.setActionCancel(getResources().getString(R.string.string_33), "cancel");
//            notificationManager.addPopup(0x0004, popup);
            DeleteBuilder deleteBuilder = null;
            try {
                deleteBuilder = helper.getFavouriteDao().deleteBuilder();
                deleteBuilder.where().eq("id", albumId);
                deleteBuilder.delete();
                GetUserFavouriteAlbumRadio();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

    }

    /**
     * 类型转换
     *
     * @param paiedAlbum
     * @return
     */
    private CommonFavouritePaiedHistoryEntity paiedAlbum2CommonFavouritePaiedHistoryEntity(PaidAlbumsEntity paiedAlbum) {
        CommonFavouritePaiedHistoryEntity result = new CommonFavouritePaiedHistoryEntity();
        result.setId(paiedAlbum.getId());
        result.setName(paiedAlbum.getAlbumTitle());
        result.setHostName(paiedAlbum.getAnnouncer().getNickname());
        result.setCoverUrlSmall(paiedAlbum.getCoverUrlSmall());
        result.setCoverUrlMiddle(paiedAlbum.getCoverUrlMiddle());
        result.setCoverUrlLarge(paiedAlbum.getCoverUrlLarge());
        result.setContentAbstract(paiedAlbum.getAlbumTags());
        result.setType("album");
        result.setFrom(2);
        return result;
    }


    private void GetAllPaiedAlbum() {
        int local_page = page_index;
        if (is_refresh) {
            local_page = 1;
        }

        /*Start by menglingqiang*/
        Date dt = new Date();
        try {
            TracelogInterface inter = MusicApplication.getLogInterface();
            if (inter != null) {
                inter.sendLogData(dt.toString(), dt.toString(), FavouritePaiedHistoryActivity.this.getClass().getName(), "DEBUG", null, "GetAllPaiedAlbum request");
            } else {
                Log.e("jgj", "inter == null");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        /*End by menglingqiang*/

        radioModel.GetAllPaiedAlbum(local_page).doOnSubscribe(new Action0() {
            @Override
            public void call() {
                showProgress();
            }
        }).subscribe(new CommonSubscriber<PaiedAlbumBean>() {
            @Override
            public void onSuccess(PaiedAlbumBean response) {
                hideProgress();
                swipe_refrsh_common.finishRefresh();
                swipe_refrsh_common.finishLoadmore();
                if ((response.getData().getPaidAlbums() != null) && (response.getData().getPaidAlbums() != null)) {
                    if (is_refresh) {
                        datas.clear();
                        page_index = 1;
                    }
                    for (PaidAlbumsEntity entity : response.getData().getPaidAlbums()) {
                        datas.add(paiedAlbum2CommonFavouritePaiedHistoryEntity(entity));
                    }
                    adapter.setDatas(dealDataFromStatus(datas));
                    page_index++;
                } else {
                    swipe_refrsh_common.finishLoadmore();
                    swipe_refrsh_common.setEnableLoadmore(false);
                }
                /*Start by menglingqiang*/
                Date dt = new Date();
                try {
                    TracelogInterface inter = MusicApplication.getLogInterface();
                    if (inter != null) {
                        inter.sendLogData(dt.toString(), dt.toString(), FavouritePaiedHistoryActivity.this.getClass().getName(), "DEBUG", "400", "GetAllPaiedAlbum onSuccess");
                    } else {
                        Log.e("jgj", "inter == null");
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                /*End by menglingqiang*/
            }

            @Override
            public void onFailure(BaseBean response) {
                hideProgress();
                swipe_refrsh_common.finishRefresh();
                /*Start by menglingqiang*/
                Date dt = new Date();
                try {
                    TracelogInterface inter = MusicApplication.getLogInterface();
                    if (inter != null) {
                        inter.sendLogData(dt.toString(), dt.toString(), FavouritePaiedHistoryActivity.this.getClass().getName(), "ERROR", "400", "GetAllPaiedAlbum onFailure");
                    } else {
                        Log.e("jgj", "inter == null");
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                /*End by menglingqiang*/
            }
        });
    }


    private void cancelFav() {

    }


    public void onEvent(DeleteFavouriteAction action) {
        if (action.getFrom() == 0) {
            CancelUserFavourite(action.getAlbumId(), "album");
        }
    }

    public void onEvent(DeleteDownloadAlbumAction action) {
        if (action.getTrackId() == 0) {
            if (!Constants.isRelease) {
                MaterialDialog dialog = new MaterialDialog.Builder(this).title(getResources().getString(R.string.string_30)).content(getResources().getString(R.string.string_115)).positiveText(getResources().getString(R.string.string_32)).negativeText(getResources().getString(R.string.string_33)).onPositive(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                        try {
                            DeleteBuilder deleteBuilder = helper.getDownloadDao().deleteBuilder();
                            deleteBuilder.where().eq("albumId", action.getAlbumId());
                            deleteBuilder.delete();

                            File file = new File(TrackUtils.getTrackDir());

                            DownloadManager downloadManager = DownloadManager.getInstance(FavouritePaiedHistoryActivity.this);
                            if (downloadManager != null) {
                                downloadManager.removeTaskByAlbumId(action.getAlbumId() + "");
                            }


                            for (File subFile : file.listFiles()) {
                                if (subFile.getName().startsWith("" + action.getAlbumId())) {
                                    subFile.delete();
                                }
                            }

                            initDownloadList();
                        } catch (SQLException e) {
                            e.printStackTrace();
                        }
                    }
                }).build();
                dialog.show();
            } else {
//                ToastUtils.show(action.getAlbumId()+"");
//                Logger.i("DeleteDownloadAlbum1-->"+action.getAlbumId());
//                NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
//                Intent setAlertIntent = new Intent("com.jpcc.vw.FavouritePaiedHistoryActivity");
//                setAlertIntent.putExtra("action", "DeleteDownloadAlbum");
//                setAlertIntent.putExtra("AlbumId", action.getAlbumId());
//                PendingIntent pendingIntent = PendingIntent.getBroadcast(FavouritePaiedHistoryActivity.this, 0, setAlertIntent, PendingIntent.FLAG_UPDATE_CURRENT);
//                Popup popup = new Popup(getResources().getString(R.string.string_30), getResources().getString(R.string.string_115));
//                popup.setActionOne(getResources().getString(R.string.string_32), pendingIntent);
//                popup.setActionCancel(getResources().getString(R.string.string_33), "cancel");
//                notificationManager.addPopup(0x0004, popup);

                try {
                    DeleteBuilder deleteBuilder = helper.getDownloadDao().deleteBuilder();
                    deleteBuilder.where().eq("albumId", action.getAlbumId());
                    deleteBuilder.delete();

                    File file = new File(TrackUtils.getTrackDir());

                    DownloadManager downloadManager = DownloadManager.getInstance(FavouritePaiedHistoryActivity.this);
                    if (downloadManager != null) {
                        downloadManager.removeTaskByAlbumId(action.getAlbumId() + "");
                    }


                    for (File subFile : file.listFiles()) {
                        if (subFile.getName().startsWith("" + action.getAlbumId())) {
                            subFile.delete();
                        }
                    }
                    initDownloadList();
                } catch (SQLException e) {
                    e.printStackTrace();
                }


            }
        }
    }


    private void getLiveingProgramDetail(long radioId, String radioName) {
        Date today = new Date();
        Calendar c = Calendar.getInstance();
        c.setTime(today);
        int weekday = c.get(Calendar.DAY_OF_WEEK);

        Observable.zip(radioModel.GetPlayingProgramDetail(radioId), radioModel.getLiveSchedules(radioId, weekday - 1), new Func2<LiveRadioDetailBean, RadioDeailBean, RadioSumBean>() {
            @Override
            public RadioSumBean call(LiveRadioDetailBean liveRadioDetailBean, RadioDeailBean radioDeailBean) {
                RadioSumBean response = new RadioSumBean();
                if (liveRadioDetailBean.getCode() == 0 && radioDeailBean.getCode() == 0) {
                    response.setLiveRadio(liveRadioDetailBean);
                    response.setRadioSchedule(radioDeailBean);
                    return response;
                }
                return response;
            }
        }).subscribe(new Subscriber<RadioSumBean>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onNext(RadioSumBean radioSumBean) {
                List<Track> sources = new ArrayList<>();


                if (radioSumBean.getRadioSchedule() != null && radioSumBean.getRadioSchedule().getData() != null) {
                    for (RadioDeailBean.RadioSchedule schedule : radioSumBean.getRadioSchedule().getData()) {
                        if (!TextUtils.isEmpty(schedule.getListenBackUrl())) {
                            Track track = new Track();
                            SubordinatedAlbum subordinatedAlbum = new SubordinatedAlbum();
                            subordinatedAlbum.setId(radioId);
                            subordinatedAlbum.setAlbumTitle(radioName);
                            Announcer announcer = new Announcer();
                            announcer.setNickname("");
                            track.setId(schedule.getId());
                            track.setTrackTitle(schedule.getRelatedProgram().getProgramName());
                            track.setCoverUrlLarge(schedule.getRelatedProgram().getBackPicUrl());
                            track.setPlayUrl32(schedule.getListenBackUrl());
                            track.setCanDownload(false);
                            track.setDownloadUrl("");
                            track.type = "radio";
                            track.setSubordinatedAlbum(subordinatedAlbum);
                            track.setAnnouncer(announcer);
                            track.setLive(false);


                            SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
                            long endInt = 0;
                            long startInt = 0;
                            try {
                                if (schedule.getEndTime().equals("00:00")) {
                                    schedule.setEndTime("24:00");
                                }
                                Date end = sdf.parse(schedule.getEndTime());
                                endInt = end.getTime();
                                Date start = sdf.parse(schedule.getStartTime());
                                startInt = start.getTime();
                                Logger.i("endtime-startTime--->" + (endInt - startInt) / 1000);
                            } catch (ParseException e) {
                                e.printStackTrace();
                            }
                            track.setStartTime(schedule.getStartTime());
                            track.setEndString(schedule.getEndTime());
                            track.setDuration((endInt - startInt) / 1000);


                            sources.add(track);
                        }
                    }
                }


                Track liveRadio = new Track();
                if (radioSumBean.getLiveRadio() != null) {
                    LiveRadioDetailBean response = radioSumBean.getLiveRadio();
                    SubordinatedAlbum subordinatedAlbum = new SubordinatedAlbum();
                    subordinatedAlbum.setId(radioId);
                    subordinatedAlbum.setAlbumTitle(radioName);
                    Announcer announcer = new Announcer();
                    announcer.setNickname("");
                    liveRadio.setId(response.getData().getId());
                    liveRadio.setTrackTitle(response.getData().getProgramName());
                    liveRadio.setCoverUrlLarge(response.getData().getBackPicUrl());
                    liveRadio.setPlayUrl32(response.getData().getRate24AacUrl());
                    liveRadio.setCanDownload(false);
                    liveRadio.setDownloadUrl("");
                    liveRadio.type = "radio";
                    liveRadio.setSubordinatedAlbum(subordinatedAlbum);
                    liveRadio.setAnnouncer(announcer);
                    liveRadio.setLive(true);
                }
                Constants.LastModeFlag = false;
//                AlbumRadioAudioPlayer.get().setOnSources(sources, 0, 4, -1);
                AlbumRadioAudioPlayer.get().setOnSourcesForRadio(sources, liveRadio, true, 0);
                adapter.notifyDataSetChanged();

            }
        });
    }


    public void onEvent(RadioItemSelectedAction action) {

        /*Start by menglingqiang*/
        Date dt = new Date();
        try {
            TracelogInterface inter = MusicApplication.getLogInterface();
            if (inter != null) {
                inter.sendLogData(dt.toString(), dt.toString(), FavouritePaiedHistoryActivity.this.getClass().getName(), "DEBUG", null, "GetPlayingProgramDetail request");
            } else {
                Log.e("jgj", "inter == null");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        getLiveingProgramDetail(action.getRadioId(), action.getRadioName());
    }

    @Override
    protected void onDestroy() {
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
        this.unregisterReceiver(receiver);
        super.onDestroy();
    }


    public void onEvent(WaveAction action) {
        adapter.notifyDataSetChanged();
    }
}
